package my.study.java.lang.reflect.Proxy.examples;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class DynamicProxyHandler implements InvocationHandler {
	private Object proxied;
	private Map<String, Integer> map = new HashMap<String, Integer>();

	public  DynamicProxyHandler(Object proxied) {
		this.proxied = proxied;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		pl("**** proxy: " + proxy.getClass().getName()
				+ ", method: " + method.getName() + ", args: " + ts(args));
		if (map.get(method.getName()) == null) {
			map.put(method.getName(), 1);
		} else {
			map.put(method.getName(), map.get(method.getName()) + 1);
		}
		pl(map);
		return method.invoke(proxied, args);
	}
	public static void pl(Object o) {
		System.out.println(o);
	}
	public static String ts(Object[] os) {
		StringBuilder sb = new StringBuilder("[");
		if (os == null || os.length == 0) {
			
		} else	{
			sb.append(os[0]);
			for (int i = 1; i < os.length; i++) {
				sb.append(", " + os[i]);
			}
		}
		sb.append("]");
		return sb.toString();
	}
}
